import React, {useState, useEffect, useRef} from 'react';
import {View, Text, StyleSheet, TextInput, Alert} from 'react-native';
import {Button, Input} from '@rneui/themed';
import {sendByEmail, forgetPassword, sendByPhone} from '@/apis/api';
import Overlay from '@/components/Overlay';
import {connect} from 'react-redux';
import {handleLogout} from '@/store/action/user';
import Toast from 'react-native-root-toast';
import {useTranslation} from 'react-i18next';

function ForgetPasswordScreen({navigation, handleLogout}) {
  const {t} = useTranslation();
  const [receiver, setReceiver] = useState('');
  const [countSecond, setCountSecond] = useState(60); // 验证码计时
  const [isShowCode, setIsShowCode] = useState(false);
  const [validateCode, setValidateCode] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [codeType, setCodeType] = useState('');
  let intervalHandle = useRef();
  useEffect(() => {
    navigation.setOptions({
      headerShown: true,
      headerBackVisible: true,
    });
    return () => {
      // 清除定时器
      clearInterval(intervalHandle.current);
    };
  }, []);
  const handleChangePassword = () => {
    if (password.length < 8 || password.length > 16) {
      Toast.show(t('sys_pwdLengthTip'), {
        duration: 1000,
        position: Toast.positions.CENTER,
      });
      return;
    } else if (password !== confirmPassword) {
      Toast.show(t('sys_twoPasswordUnmatch'), {
        duration: 1000,
        position: Toast.positions.CENTER,
      });
      return;
    }
    handleForgetPassword();
  };
  const handleForgetPassword = async () => {
    setIsLoading(true);
    const params = {
      password,
      validateCode,
      receiver,
    };
    try {
      const res = await forgetPassword(params);
      navigation.navigate('Login');
    } catch (err) {
    } finally {
      setIsLoading(false);
    }
  };

  //发送邮箱验证码
  const getCode = async () => {
    const regMobile = /(^1[3|4|5|7|8|9]\d{9}$)|(^0\d{2,3}-?\d{7,8}$)/;
    const regEmail = /^([a-zA-Z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    if (regMobile.test(receiver)) {
      const params = {
        phone: receiver,
        codeType: '变更密码',
      };
      const res = await sendByPhone(params);
      if (res.code === 0 || res.code === 200) {
        handleCountDown();
      }
    } else if (regEmail.test(receiver)) {
      setCodeType('email');
      const params = {
        email: receiver,
        type: '变更密码',
      };
      const res = await sendByEmail(params);
      if (res.code === 0 || res.code === 200) {
        handleCountDown();
      }
    } else {
      Toast.show(t('sys_mobileOrEmailWrongFormat'), {
        duration: 1000,
        position: Toast.positions.CENTER,
      });
    }
  };

  const handleCountDown = () => {
    if (isShowCode) {
      // 倒计时未结束,不能重复点击
      return;
    }
    //倒计时
    setIsShowCode(true);
    intervalHandle.current = setInterval(() => {
      setCountSecond(preSecond => {
        if (preSecond <= 1) {
          setIsShowCode(false);
          clearInterval(intervalHandle.current);
          // 重置秒数
          return 60;
        }
        return preSecond - 1;
      });
    }, 1000);
  };

  return (
    <View style={styles.container}>
      <Overlay isShow={isLoading} />
      <Text style={styles.title}>{t('sys_forgetPassword')}</Text>
      <View style={styles.content}>
        <TextInput
          style={styles.input}
          placeholder={t('sys_plsInputMobileOrEmail')}
          value={receiver}
          onChangeText={setReceiver}
        />
        <View style={styles.validCode}>
          <TextInput
            style={[styles.input, styles.validInput]}
            placeholder={t('sys_plsInputVerificationCode')}
            value={validateCode}
            onChangeText={setValidateCode}
          />
          <Button
            style={styles.sendBtn}
            radius={'sm'}
            size="sm"
            title={
              !isShowCode
                ? t('sys_getVerificationCode')
                : t('sys_sendVerificationCodeTimeTip', {second: countSecond})
            }
            disabled={isShowCode || !receiver}
            onPress={getCode}
          />
        </View>

        <TextInput
          style={styles.input}
          placeholder={t('sys_plsInputNewPwd')}
          value={password}
          onChangeText={setPassword}
          secureTextEntry
        />
        <TextInput
          style={styles.input}
          placeholder={t('sys_plsConfirmNewPwd')}
          value={confirmPassword}
          onChangeText={setConfirmPassword}
          secureTextEntry
        />
        <Button
          radius={'md'}
          size="md"
          title={t('sys_modify')}
          disabled={!confirmPassword || !password || !receiver || !validateCode}
          onPress={handleChangePassword}
        />
      </View>
    </View>
  );
}

export default connect(
  state => ({
    userInfo: state.user.userInfo,
    auth: state.user.auth,
  }),
  dispatch => ({
    handleLogout: () => dispatch(handleLogout()),
  }),
)(ForgetPasswordScreen);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
  },
  content: {
    width: '85%',
    marginLeft: 'auto',
    marginRight: 'auto',
  },
  title: {
    fontSize: 24,
    color: '#333',
    marginBottom: 20,
  },
  validCode: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },

  sendBtn: {
    width: 100,
  },
  input: {
    height: 40,
    borderWidth: 1,
    borderColor: '#ccc',
    marginBottom: 20,
    borderRadius: 5,
    padding: 10,
  },
  validInput: {
    flex: 1,
    marginRight: 20,
    marginBottom: 0,
  },
});
